package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.service.MemberService;
import com.itheima.service.OrderService;
import com.itheima.utils.RASUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 登录
 */
@RestController
@RequestMapping("/login")
public class LoginController {

    @Autowired
    private JedisPool jedisPool;

    @Reference
    private MemberService memberService;

    @Reference
    private OrderService orderService;


    /**
     * 是否登录
     *
     * @param response
     * @param request
     * @return
     */
    @RequestMapping("/isLogin")
    public Result isLogin(HttpServletResponse response, HttpServletRequest request) {
        String telephone = null;
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            telephone = getRealPhoneNum(cookies);

            //查询数据库是否有该用户
            Member member = memberService.findByTelephone(telephone);

            //从redis中获取用户
            String memberStr = jedisPool.getResource().get(telephone);
            System.out.println(memberStr);
            Member memberS = JSON.parseObject(memberStr, Member.class);

            //如果数据库中和redis中用户是否相同
            if (memberS != null && telephone.equals(memberS.getPhoneNumber())) {
                return new Result(true, null, member);
            }
        }

        return new Result(false, null);
    }

    /**
     * 验证老手机号
     *
     * @param map
     * @return
     */
    @RequestMapping("/checkOld")
    public Result checkOld(@RequestBody Map map) {
        //@RequestParam("telephone") String telephone, @RequestParam("validateCode") String validateCode
        String telephone = (String) map.get("telephone");
        String validateCode = (String) map.get("validateCode");

        //1.获取redis中验证码
        String loginCode = jedisPool.getResource().get(telephone + RedisMessageConstant.SENDTYPE_CHANGE);
        if (!Objects.equals(loginCode, validateCode)) {
            //验证码错误
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        } else {
            return new Result(true, MessageConstant.SEND_VALIDATECODE_SUCCESS);
        }
    }

    /**
     * 更改新手机号
     *
     * @param map
     * @return
     */
    @RequestMapping("/changePhoneNumber")
    public Result changePhoneNumber(@RequestBody Map map,HttpServletResponse response) {
        String telephone = (String) map.get("newPhoneNum");
        String oldTelephone = (String) map.get("oldPhoneNum");
        String validateCode = (String) map.get("validateCode");

        //1.验证码是否正确
        //1.获取redis中验证码
        String changeCode = jedisPool.getResource().get(telephone + RedisMessageConstant.SENDTYPE_CHANGE);
        if (!Objects.equals(changeCode, validateCode)) {
            //验证码错误
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }

        try {
            //2.根据老手机号,修改数据库
            Member member = memberService.changePhoneNumber(map);

            //将修改后的手机号响应到cookie.并存入redis
            //保存会员信息到Redis中
            String json = JSON.toJSON(member).toString();
            jedisPool.getResource().setex(telephone, 60*30, json);

            //**加密手机号存入cookie**
            telephone = RASUtils.encryptData(telephone);
            //写入Cookie，跟踪用户
            Cookie cookie = new Cookie("telephone",telephone);
            cookie.setPath("/");//路径
            cookie.setMaxAge(60 * 60 * 24 * 30);//有效期30天
            response.addCookie(cookie);

            return new Result(true, MessageConstant.EDIT_MEMBER_SUCCESS, member);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.EDIT_MEMBER_FAIL);
        }
    }

    /**
     * 更新个人信息
     *
     * @param member
     * @return
     */
    @RequestMapping("/editMemberInfo")
    public Result editMemberInfo(@RequestBody Member member) {

        try {
            Member m = memberService.update(member);
            return new Result(true, MessageConstant.EDIT_MEMBER_SUCCESS, m);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.EDIT_MEMBER_FAIL);
        }
    }

    /**
     * 根据日期查询预约记录
     *
     * @param dates
     * @param request
     * @return
     */
    @RequestMapping("/findCondition")
    public Result findCondition(@RequestBody  Map<String, Date> dates, HttpServletRequest request){
        try {
            Cookie[] cookies = request.getCookies();
            String realPhoneNum = getRealPhoneNum(cookies);
            List list = orderService.findCondition(dates,realPhoneNum);
            return new Result(true, MessageConstant.QUERY_ORDER_SUCCESS,list);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(true, MessageConstant.QUERY_ORDER_FAIL);
        }
    }

    /**
     * 从cookies中获取手机号
     *
     * @param cookies
     * @return
     */
    private String getRealPhoneNum(Cookie[] cookies){
        String telephone =null;
        if (cookies!=null){
            for (Cookie cookie : cookies) {
                String name = cookie.getName();
                if ("telephone".equals(name)) {
                    telephone = cookie.getValue();
                    //**解密手机号**
                    telephone = RASUtils.decryptData(telephone);
                    break;
                }
            }
        }
        return telephone;
    }
}
